package com.platform.study.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * Created with IntelliJ IDEA.
 * User: wangyanginfo
 * Date: 12-11-26
 * Time: 下午5:28
 */
public class ConcurrentSimple implements Runnable {

    private int ticket = 5000;  //10张票

    @Override
    public void run() {
        while (ticket > 0) {
            synchronized (this) {
                method();
            }
        }
    }

    /**
     * 下面的方法会造成票数为负数
     */
    private void method() {
        if (ticket > 0) {
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " 运行 _  " + ticket--);
        }
    }

    public static void main(String[] args) {
        ConcurrentSimple simple = new ConcurrentSimple();
        //设置特定的线程池，大小为5
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        threadPool.execute(simple);
        threadPool.execute(simple);
        threadPool.execute(simple);
        threadPool.shutdown();

        Future future = threadPool.submit(simple);
        future.cancel(true);
    }
}